package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.dto.RequestParams;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import cn.itcast.hotel.vo.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    //注入与es链接
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams requestParams) throws IOException {
        //1 创建搜索对象
        SearchRequest request = new SearchRequest("hotel");
        //2创建DSL语句
        createDSL(requestParams, request);
        //3 发送请求
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        return getPageResult(search);
    }

    /**
     * 解析数据
     *
     * @param search
     * @return
     */
    private static PageResult getPageResult(SearchResponse search) {
        //3 解析返回数据
        SearchHits hits = search.getHits();
        long value = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
        List docList = new ArrayList<HotelDoc>();
        for (SearchHit hit : hits1) {
            String sourceAsString = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);

            //设置距离显示参数
            Object[] sortValues = hit.getSortValues();
            if (sortValues != null && sortValues.length != 0) {
                hotelDoc.setDistance(sortValues[0]);
                System.out.println(sortValues[0]);
            }
            //高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null && !highlightFields.isEmpty()) {
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    String string = highlightField.getFragments()[0].toString();
                    hotelDoc.setName(string);
                }
            }
            docList.add(hotelDoc);
        }
        //4 构建PageResult
        PageResult pageResult = new PageResult();
        pageResult.setTotal(value);
        pageResult.setHotels(docList);
        return pageResult;
    }

    /**
     * 船舰DSL语句
     *
     * @param requestParams
     * @param request
     */
    private static void createDSL(RequestParams requestParams, SearchRequest request) {
        //1:获取请求参数对象的成员变量
        String key = requestParams.getKey();
        Integer size = requestParams.getSize();
        Integer page = requestParams.getPage();
        String sortBy = requestParams.getSortBy();

        String brand = requestParams.getBrand();
        String starName = requestParams.getStarName();
        String location = requestParams.getLocation();
        String city = requestParams.getCity();
        Integer minPrice = requestParams.getMinPrice();
        Integer maxPrice = requestParams.getMaxPrice();

        //检查是否有每个字段的参数  有就设置
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (StringUtils.isEmpty(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }

        if (!StringUtils.isEmpty(city)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("city", city));
        }
        if (!StringUtils.isEmpty(brand)) {
            boolQueryBuilder.should(QueryBuilders.termQuery("brand", brand));
        }
        if (!StringUtils.isEmpty(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }
        if (!StringUtils.isEmpty(minPrice)) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice));
        }
        if (!StringUtils.isEmpty(maxPrice)) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice));
        }

        //附近的酒店
        if (!StringUtils.isEmpty(location)) {
            GeoDistanceSortBuilder location1 = SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS);
            request.source().sort(location1);
        }

        if (sortBy.equals("score")) {
            request.source().sort("score", SortOrder.DESC);
        }  else if(sortBy.equals("price")) {
            request.source().sort("price", SortOrder.ASC);
        }

        //算分  让交钱的用户出现在头部  ！！！ 这个地方不是很懂哦！！！！！！
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),//算分函数过滤条件，满足条件才会加分
                                ScoreFunctionBuilders.weightFactorFunction(5)       //权重多少分
                        )
                }
        );


        //高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));


//        request.source().query(boolQueryBuilder);


        //分页
        request.source().from((page - 1) * size).size(size);

        //执行算分
        request.source().query(functionScoreQueryBuilder);

    }
}
